#[allow(warnings)]
fn main() {
    use doe::*;
    if (args!().len() == 1 && &args!()[0] == "-h") || args!().len()<1{
        println!("Usage:");
        println!("cargo r -- -h  => display help");
        println!("cargo r -- deploy  => deploy to gitee");
        println!("cargo r -- get_img  => get all images to blog_images repo");
    } 
    else if args!().len() == 1 && &args!()[0] == "get_img" {
        let repo_path = "./src/posts";
        doe::fs::fs::walk_dir(repo_path)
            .unwrap()
            .iter()
            .for_each(|p| {
                if p.display().to_string().ends_with("md"){
                    std::fs::read_to_string(p).unwrap().split_to_vec("\n").iter().for_each(|line|{
                        if line.contains(".image") && line.contains("p3-juejin.byteimg"){
                            if let Some(url) = extract_image_url(line){
                                    let file_name = url.split("/").last().unwrap().replace(".image", ".png");
                                    download_image(&url, &"../blog_images/all_imgs/".push_back(file_name.clone()));
                            }
                        }
                    });
                }
            });
    }
    else if args!().len() == 1 && &args!()[0] == "deploy" {
        system("mdbook build").unwrap();
        let deploy_path = "../dnrops";
        doe::fs::fs::walk_dir(deploy_path)
            .unwrap()
            .iter()
            .for_each(|p| {
                if p.starts_with("../dnrops/.git/") {
                } else {
                    doe::remove_file_or_folder!(p);
                }
            });
        // frist cretae dirs
        doe::fs::fs::walk_dir("./book")
            .unwrap()
            .iter()
            .for_each(|p| {
                if p.is_dir() {
                    doe::fs::fs::move_folder(
                        p,
                        &deploy_path
                            .to_path_buf()
                            .join(p.strip_prefix("./book").unwrap()),
                    )
                    .unwrap();
                }
            });
        // secondary move files
        doe::fs::fs::walk_dir("./book")
            .unwrap()
            .iter()
            .for_each(|p| {
                if !p.is_dir() {
                    doe::fs::fs::move_file(
                        p,
                        &deploy_path
                            .to_path_buf()
                            .join(p.strip_prefix("./book").unwrap()),
                    )
                    .unwrap();
                }
            });
        // push blog
        system("ppush new").unwrap();

        std::env::set_current_dir("../dnrops").unwrap();
        // push page
        system("ppush new").unwrap();
    }
}

#[allow(warnings)]
fn download_image(url: &str, save_path: &str) {
    use std::io::Write;
    let mut resp = reqwest::blocking::get(url).unwrap();
    let buf = resp.bytes().unwrap().to_vec();
    let mut file = std::fs::File::create(save_path).unwrap();
    file.write_all(&buf).unwrap();
    println!("{},done!",url);
}
#[allow(warnings)]
fn extract_image_url(input: &str) -> Option<String> {
    // Extract the URL between parentheses
    let re = regex::Regex::new(r"\(([^)]+)\)").unwrap();
    if let Some(captures) = re.captures(input) {
        let url_str = captures.get(1).unwrap().as_str();

        // Parse the URL using the `url` crate
        let mut url = url::Url::parse(url_str).ok()?;

        // Remove the query parameters and anchor tag
        url.set_query(None);
        url.set_fragment(None);

        Some(url.to_string())
    } else {
        None
    }
}
